<?php

declare(strict_types=1);


namespace App\Services\Redirect;


use App\Models\DeviceServiceProviders;
use App\Services\PengYiPeng\ThridLiteService;

class AliyunRedirectService
{
    //处理阿里云跳转的code
    //{"app_id":"2021004167603274","source":"alipay_app_auth","state":"STORE_ID_VALUE","app_auth_code":"P821ebc0f499c4be496ea2978af92164"}
    public function alipayAppAuth(array $data): string
    {
        try {
            $app_id = $data["app_id"];
            if ($app_id != config("lite.threePartyApplication.appId")) {
                throw new \Exception("APPID不匹配");
            }
            //不确定这个参数是否存在
//            $state = $data["state"];
            $code = $data["app_auth_code"];
            //通过code置换token
            $service = new ThridLiteService();
            list($providerPid,$providerAPPID,$app_auth_token)= $service->createAppAuthToken($code);
            $provider = DeviceServiceProviders::query()->where(["pid" => $providerPid, "app_id" => $providerAPPID])->first();
            if (empty($provider)) {
                throw new \Exception('授权服务商不存在');
            }
            $provider->app_auth_code = $code;
            $provider->app_auth_token = $app_auth_token;
            $provider->is_auth = 1;
            $provider->save();
            return '<div style="text-align:center;"><img src="/layuiadmin/img/auth_success.png" style="width:350px;height:350px;padding:50% 0 100px 0;"  /><div style="font-size:56px">授权成功</div></div>';
        } catch (\Exception $e) {
//            return $e->getMessage();
            return '<div style="text-align:center;"><img src="/layuiadmin/img/auth_error.png" style="width:350px;height:350px;padding:50% 0 100px 0;"  /><div style="font-size:56px">'.$e->getMessage().'</div></div>';
        }
    }

}